package com.woniuxy.myshop.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniuxy.myshop.entity.Address;
import com.woniuxy.myshop.entity.Order;
import com.woniuxy.myshop.entity.User;
import com.woniuxy.myshop.mapper.AddressMapper;
import com.woniuxy.myshop.mapper.CartMapper;
import com.woniuxy.myshop.mapper.ItemMapper;
import com.woniuxy.myshop.mapper.OrderMapper;
import com.woniuxy.myshop.vo.CartVo;
import com.woniuxy.myshop.vo.ItemVo;
import com.woniuxy.myshop.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Service
public class OrderService {
    @Autowired
    AddressMapper addressMapper ;

    @Autowired
    CartMapper cartMapper ;

    @Autowired
    OrderMapper orderMapper;

    @Autowired
    ItemMapper itemMapper ;

    @Transactional
    public void addOrder(int[] idArr, User user,int aid) {
        //查询地址对象
        Address address = addressMapper.selectByPrimaryKey(aid);
        //封装一个 Order对象
        OrderVo order = new OrderVo();
        order.setAddress(address);
        order.setUser(user);
        order.setCreatedate(new Date());
        order.setStatus(1); // 未支付
        String orderNum = "WONIU"+System.currentTimeMillis();
        order.setOrdernum(orderNum);
        //设置总价格
        List<CartVo> list = cartMapper.selectSubmitMyCart(idArr,user.getId());
        double all = 0.0 ;
        for(CartVo c :list){
            double price = c.getProduct().getPrice()*c.getBuycount();
            all += price ;
        }
        order.setAllprice(all);
        //先插入 订单 并且把 订单id 返回
        orderMapper.insertOrder(order);

        //封装订单明细集合
        Set<ItemVo> items = new HashSet<>();
        for (CartVo c :list){
            ItemVo itemVo = new ItemVo();
            itemVo.setOrder(order); //
            itemVo.setBuycount(c.getBuycount());
            itemVo.setPrice(c.getProduct().getPrice());
            itemVo.setProduct(c.getProduct());
            items.add(itemVo);
        }
        //插入订单明细
        itemMapper.insertBatch(items);
        //删除购物车中的商品
        cartMapper.deleteSubmitMyCart(idArr,user.getId());
    }

    public PageInfo<OrderVo> queryOrderByPage(Integer now, Integer size, String orderNum,int userid) {
        PageHelper.startPage(now,size);
        List<OrderVo> list = orderMapper.selectOrderByUser(orderNum,userid);
        return new PageInfo<>(list);
    }
}
